package com.tourism.home.service;

import com.tourism.home.utils.SFTPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Service
public class UploadService {
    @Autowired
    HttpServletRequest httpServletRequest;

    final String HOST = "123.207.19.115";
    final Integer PORT = 9559;
    final String USERNAME = "wll";
    final String PASSWORD = "cptbtptp";

    public boolean uploadIcon(MultipartFile file){
        HttpSession session = httpServletRequest.getSession();
        String realName;
        String fileName = file.getOriginalFilename();
        String fileNameExt = fileName.substring(fileName.indexOf("."), fileName.length());
        realName = UUID.randomUUID().toString() + fileNameExt;
        SFTPUtil sftpUtil = new SFTPUtil();
        try {
            sftpUtil.connect(HOST,PORT,USERNAME,PASSWORD);
            sftpUtil.upload("/home/wll/projects/upload/user_icon/",realName,file.getInputStream());
            sftpUtil.logout();
            String link="http://123.207.19.115:8888/user_icon/"+realName;
            session.setAttribute("icon",link);
        }catch (Exception e){
            // TODO: handle exception
        }
        return true;
    }

    public boolean uploadimage(MultipartFile file){
        HttpSession session = httpServletRequest.getSession();
        String realName;
        String fileName = file.getOriginalFilename();
        System.out.println(fileName.length());
        String fileNameExtension = fileName.substring(fileName.indexOf("."), fileName.length());
        System.out.println(fileName);
        System.out.println(fileNameExtension);
        realName = UUID.randomUUID().toString() + fileNameExtension;
        SFTPUtil sftpUtil = new SFTPUtil();
        try {
            sftpUtil.connect(HOST,PORT,USERNAME,PASSWORD);
            sftpUtil.upload("/home/wll/projects/upload/image/",realName,file.getInputStream());
            sftpUtil.logout();
            String[] data={"http://123.207.19.115:8888/image/"+realName};
            session.setAttribute("data",data);
        }catch (Exception e){
            // TODO: handle exception
        }
        return true;
    }
}
